﻿using IService;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Server
{
    public partial class ChatService : IChatService
    {
        public async Task<string> Query(string id, int seconds)
        {
            string userName = GetUserInfo().Name;
            Console.WriteLine($"{userName} query data {id} in {seconds}s. at {DateTime.Now.ToString("HH:mm:ss.fff")}");
            await Task.Delay(seconds * 1000);
            string message = $"{userName} query {id} returned in {seconds}s. at {DateTime.Now.ToString("HH:mm:ss.fff")}.";
            Console.WriteLine(message);
            return message;
        }

    }

    partial class ChatService:ControllerBase
    {

    }



    partial class ChatService
    {
        public async Task Say(string someOne, string message)
        {
            await Task.Run(() => Console.WriteLine($"{someOne} said:{message}"));
        }

        static readonly ConcurrentDictionary<string, UserInfo> cache = new ConcurrentDictionary<string, UserInfo>();

        public async Task<UserInfo> SignIn(string token)
        {
            return await Task.Run<UserInfo>(() =>
            {
                if (!cache.ContainsKey(token))
                {
                    Thread.Sleep(1000);
                    UserInfo dbUser = new UserInfo()
                    {
                        IsAuthenticated = true
                        ,
                        Name = Guid.NewGuid().ToString().Split('-').FirstOrDefault()
                    };
                    cache.AddOrUpdate(token, dbUser, (x, y) => dbUser);
                }
                return cache[token];
            });
            //SynchronizationContext 
            //ExecutionContext 
        }

        public async Task SayTo(string someOne, string message, string to)
        {
            await Task.Run(() => Console.WriteLine($"{someOne} said to {to}:{message}"));
        }


        public async Task Delay(int seconds)
        {
            string id = GetUserInfo().Name;
            await Task.Run(() =>
            {
                Console.WriteLine($"{id} want delay {seconds}s.");
                Thread.Sleep(seconds * 1000);
                Console.WriteLine($"{id} delayed {seconds}s.");
            });

        }


        public async Task<List<UserInfo>> Complex()
        {
            return await Task.Run<List<UserInfo>>(() =>
            {

                return new List<UserInfo>();
            });
        }


    }

    public class ControllerBase
    {
        public UserInfo GetUserInfo()
        {
            return new UserInfo();
        }
        
    }
}
